const {
  mock
} = require("mockjs");
const Common = require("../common/index");
const dbo = require("../common/database");
class Service extends Common {
  constructor() {
    super("members");
  }

  async add(ctx) {
    try {
      let data = {
        ...ctx.params,
        memberId: this.uuid(),
      }
      let res = await dbo.insertOne("members", data);
      ctx.body = this.handleSuccess(res);
    } catch (error) {
      ctx.body = this.handleError(error);
    }
  }

  async list(ctx) {
    let {
      pageSize = 7, currPage = 1
    } = ctx.params;
    delete ctx.params.pageSize;
    delete ctx.params.currPage;
    try {
      let list = await dbo.findListByPage("members", pageSize, currPage, {});
      let total = await dbo.count('members');
      ctx.body = {
        currPage,
        pageSize,
        total,
        code: 200,
        msg: "success",
        data: list,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: error.message,
      };
    }
  }

  async all(ctx) {
    try {
      let list = await dbo.findList("members", {});
      let total = await dbo.count('members');
      list.forEach(item => {
        delete item._id;
      })
      ctx.body = {
        total,
        code: 200,
        msg: "success",
        data: list,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: error.message,
      };
    }
  }

  async find(ctx) {
    try {
      let list = await dbo.findList("members", ctx.params);
      let total = await dbo.count('members');
      ctx.body = {
        total,
        code: 200,
        msg: "success",
        data: list,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: error.message,
      };
    }
  }

  async edit(ctx) {
    let {
      memberId
    } = ctx.params;
    delete ctx.params._id;
    ctx.params.updateTime = Date.now();
    try {
      let res = await dbo.updateOne("members", {
        memberId
      }, ctx.params);
      ctx.body = {
        code: 200,
        msg: "success",
        data: res,
      };
    } catch (error) {
      ctx.body = this.handleError(error);
    }
  }

  async detail(ctx) {
    let {
      memberId
    } = ctx.params;
    try {
      let res = await dbo.findOne("members", {
        memberId
      });
      ctx.body = {
        code: 200,
        msg: "success",
        data: res,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: error.message,
      };
    }
  }

  async del(ctx) {
    try {
      let res = await dbo.deleteOne("members", ctx.params);
      let msg = res.deletedCount > 0 ? '删除成功' : '删除失败';
      ctx.body = {
        code: 200,
        msg,
        data: res,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: error.message,
      };
    }
  }
}
module.exports = new Service();